import { ref } from 'vue'
import type { Position } from '../types/chess'

interface ChessMove {
  from: Position
  to: Position
  piece: string
}

export function useChessNetwork() {
  const ws = ref<WebSocket | null>(null)
  const isConnected = ref(false)
  const roomId = ref<string | null>(null)
  const playerColor = ref<'white' | 'black' | null>(null)

  const connect = (url: string) => {
    ws.value = new WebSocket(url)
    
    ws.value.onopen = () => {
      isConnected.value = true
    }
    
    ws.value.onclose = () => {
      isConnected.value = false
      roomId.value = null
      playerColor.value = null
    }
  }

  const createRoom = () => {
    if (!ws.value) return
    ws.value.send(JSON.stringify({ type: 'create_room' }))
  }

  const joinRoom = (id: string) => {
    if (!ws.value) return
    ws.value.send(JSON.stringify({ type: 'join_room', roomId: id }))
  }

  const sendMove = (move: ChessMove) => {
    if (!ws.value || !roomId.value) return
    ws.value.send(JSON.stringify({
      type: 'move',
      roomId: roomId.value,
      move
    }))
  }

  const disconnect = () => {
    if (ws.value) {
      ws.value.close()
      ws.value = null
    }
  }

  return {
    isConnected,
    roomId,
    playerColor,
    connect,
    createRoom,
    joinRoom,
    sendMove,
    disconnect
  }
} 